<template>
  <div class="vehicle-dispatch bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">指令下达</h2>
    <!--  -->
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="专家" name="专家">
        <!-- Search Bar -->
        <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
          <QueryForm :model="search" :formItems="formItems" @search="searchVehicles" @reset="resetSearch" />
        </div>
        <!-- Action Buttons -->
        <div class="mb-4 space-x-2">
          <!-- <button @click="openAddDialog" class="bg-primary text-primary-foreground px-4 py-2 rounded">新增</button> -->
          <!-- <el-button type="danger" @click="deleteSelected">删除</el-button> -->

          <el-button @click="exportData(vehicles, '指令下达-专家', selectedIds)">导出</el-button>
        </div>
        <!--  -->
        <el-table v-loading="loading" :data="displayedVehicles" @selection-change="handleSelectionChange"
          style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
          :row-key="rowKey">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>

          <el-table-column prop="TRANSFER_NUMBER" label="调拨单号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="INCIDENT_NAME" label="事故名称" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.MSG_RELEASE_DATE).format('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column prop="EXPERT_NAME" label="专家姓名" header-align="center" align="center"></el-table-column>
          <el-table-column prop="DESTINATION_ALLOCATION" label="调配目的地" header-align="center"
            align="center"></el-table-column>
          <el-table-column prop="DEPARTURE_TIME" label="出发时间" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.DEPARTURE_TIME).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column width="300" prop="APPLICANT" label="申请人" header-align="center"
            align="center"></el-table-column>
          <el-table-column width="300" prop="APPLICATION_TIME" label="申请时间" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.APPLICATION_TIME).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column width="300" prop="APPLICATION_NOTES" label="申请原因" header-align="center"
            align="center"></el-table-column>
        </el-table>
        <!-- Pagination -->
        <Pagination v-if="vehicles.length" :tableData="vehicles" @alltabledata="alltabledata" />
      </el-tab-pane>
      <el-tab-pane label="队伍" name="队伍">
        <!-- Search Bar -->
        <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
          <QueryForm :model="search" :formItems="formItems" @search="searchVehicles" @reset="resetSearch" />
        </div>
        <!-- Action Buttons -->
        <div class="mb-4 space-x-2">
          <!-- <button @click="openAddDialog" class="bg-primary text-primary-foreground px-4 py-2 rounded">新增</button> -->
          <!-- <el-button type="danger" @click="deleteSelected">删除</el-button> -->

          <el-button @click="exportData(vehicles, '指令下达-队伍', selectedIds)">导出</el-button>
        </div>
        <!--  -->
        <el-table v-loading="loading" :data="displayedVehicles" @selection-change="handleSelectionChange"
          style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
          :row-key="rowKey">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>

          <el-table-column prop="TRANSFER_NUMBER" label="调拨单号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="INCIDENT_NAME" label="事故名称" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.MSG_RELEASE_DATE).format('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column prop="TEAM_NAME" label="队伍名称" header-align="center" align="center"></el-table-column>
          <el-table-column prop="DESTINATION_ALLOCATION" label="调配目的地" header-align="center"
            align="center"></el-table-column>
          <el-table-column prop="DEPARTURE_TIME" label="出发时间" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.DEPARTURE_TIME).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column width="300" prop="APPLICANT" label="申请人" header-align="center"
            align="center"></el-table-column>
          <el-table-column width="300" prop="APPLICATION_TIME" label="申请时间" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.APPLICATION_TIME).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column width="300" prop="APPLICATION_NOTES" label="申请原因" header-align="center"
            align="center"></el-table-column>
        </el-table>
        <!-- Pagination -->
        <Pagination v-if="vehicles.length" :tableData="vehicles" @alltabledata="alltabledata" />
      </el-tab-pane>
      <el-tab-pane label="物资" name="物资">
        <!-- Search Bar -->
        <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
          <QueryForm :model="search" :formItems="formItems" @search="searchVehicles" @reset="resetSearch" />
        </div>
        <!-- Action Buttons -->
        <div class="mb-4 space-x-2">
          <!-- <button @click="openAddDialog" class="bg-primary text-primary-foreground px-4 py-2 rounded">新增</button> -->
          <!-- <el-button type="danger" @click="deleteSelected">删除</el-button> -->

          <el-button @click="exportData(vehicles, '指令下达-物资', selectedIds)">导出</el-button>
        </div>
        <!--  -->
        <el-table v-loading="loading" :data="displayedVehicles" @selection-change="handleSelectionChange"
          style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
          :row-key="rowKey">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>

          <el-table-column prop="TRANSFER_NUMBER" label="调拨单号" header-align="center" align="center"></el-table-column>
          <el-table-column prop="INCIDENT_NAME" label="事故名称" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="MATERIAL_NAME" label="物资名称" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="ADJUSTMENT_QUANTITY" label="调配数量" header-align="center" align="center"></el-table-column>
          <el-table-column prop="DEPLOY_EMERGENCY" label="调配应急库" header-align="center" align="center"></el-table-column>
          <el-table-column prop="DESTINATION_ALLOCATION" label="调配目的地" header-align="center"
            align="center"></el-table-column>
          <el-table-column width="300" prop="APPLICANT" label="申请人" header-align="center"
            align="center"></el-table-column>
          <el-table-column width="300" prop="APPLICATION_TIME" label="申请时间" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.APPLICATION_TIME).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column width="300" prop="APPLICATION_NOTES" label="申请原因" header-align="center"
            align="center"></el-table-column>
        </el-table>


        <!-- Pagination -->
        <Pagination v-if="vehicles.length" :tableData="vehicles" @alltabledata="alltabledata" />
      </el-tab-pane>
      <el-tab-pane label="指令" name="指令">
        <!-- Search Bar -->
        <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
          <QueryForm :model="searchss" :formItems="formItemsss" @search="searchVehicles" @reset="resetsSearch" />
        </div>
        <!-- Action Buttons -->
        <div class="mb-4 space-x-2">
          <!-- <button @click="openAddDialog" class="bg-primary text-primary-foreground px-4 py-2 rounded">新增</button> -->
          <!-- <el-button type="danger" @click="deleteSelected">删除</el-button> -->

          <el-button @click="exportData(vehicles, '指令下达', selectedIds)">导出</el-button>
        </div>
        <!--  -->
        <el-table v-loading="loading" :data="displayedVehicles" @selection-change="handleSelectionChange"
          style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
          :row-key="rowKey">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
          <el-table-column prop="INSTRUCTION_CODE" label="指令编码" header-align="center" align="center"></el-table-column>
          <el-table-column prop="INSTRUCTION_CONTENT" label="指令内容" header-align="center" align="center"></el-table-column>
          <el-table-column prop="INSTRUCTION_TARGET" label="指令目标" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.MSG_RELEASE_DATE).format('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column prop="EXECUTOR" label="执行人" header-align="center" align="center"></el-table-column>
          <el-table-column prop="ISSUING_PERSON" label="下达人" header-align="center" align="center"></el-table-column>
          <el-table-column prop="ISSUING_TIME" label="下达时间" header-align="center" align="center">
            <template #default="scope">
              {{ dayjs(scope.row.ISSUING_TIME).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
        </el-table>
        <!-- Pagination -->
        <Pagination v-if="vehicles.length" :tableData="vehicles" @alltabledata="alltabledata" />
      </el-tab-pane>
    </el-tabs>
    <!-- Add Vehicle Dialog -->
    <el-dialog width="600px" v-model="isAddDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'" destroy-on-close align-center
      :before-close="closeAddDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-3 gap-6">
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">车辆类型：</label>
              <el-input type="text" v-model="newVehicle.VEHICLE_TYPE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">车牌号码：</label>
              <el-input type="text" v-model="newVehicle.LICENSE_PLATE" required />

            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">出动地点：</label>
              <el-input type="text" v-model="newVehicle.START_AREA" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">驾驶员姓名</label>
              <el-input type="text" v-model="newVehicle.DRIVER_NAME" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">联系方式：</label>
              <el-input type="text" v-model="newVehicle.PHONE_NUMBER" required />
            </div>
          </div>
          <div>
            <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备注：</label>
            <el-input type="text" v-model="newVehicle.STAMP" required />
          </div>
        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addNewVehicle" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeAddDialog" style="width: 75px; height: 30px;">取消</el-button>

        </div>
      </form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import { dayjs } from "element-plus"
const apiBaseUrl = ref(proxy.$currentUrl + '/api')
import { exportData } from '#/utils/exportfile.js'
// 搜索相关
const search = ref({
  TRANSFER_NUMBER: ''
})
const formItems = ref([
  {
    label: '调拨单号：',
    model: 'TRANSFER_NUMBER',
    type: 'input',
    placeholder: '请输入',
  },

  // {
  //   label: '消息类型：',
  //   model: 'MSG_TYPE',
  //   type: 'select',
  //   placeholder: '请选择',
  //   options: [
  //     { label: '广播', value: '广播' },
  //     { label: '短信', value: '短信' },

  //   ],
  // },
])
const searchss = ref({
  INSTRUCTION_CODE: '',

})
const formItemsss = ref([
  {
    label: '指令编码：',
    model: 'INSTRUCTION_CODE',
    type: 'input',
    placeholder: '请输入',
  },
])
const activeName = ref('专家')
const loading = ref(false)
// 数据相关
const vehicles = ref([])
const allChecked = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const rowKey = (row) => row.ID // 设置行的唯一标识
// 对话框状态
const isAddDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditing = ref(false)
// 新增车辆数据
const newVehicle = ref({

})
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
// 编辑和查看车辆数据
const table = ref()

const editingVehicle = ref({})
const viewingVehicle = ref({})
const selectedIds = ref([])
// 计算属性

const displayedVehicles = ref([])
const alltabledata = (data) => {
  displayedVehicles.value = data
}
// API 用函数
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const searchVehicles = async () => {
  displayedVehicles.value = []
  try {
    if (activeName.value == '指令') {
      const response = await axios.get(`${apiBaseUrl.value}/command_issuance/search`, { params: searchss.value })
      vehicles.value = response.data.map(vehicle => ({ ...vehicle, checked: false }))
    } else if (activeName.value == '专家') {
      const response = await axios.get(`${apiBaseUrl.value}/command_issuance/experts/search`, { params: search.value })
      vehicles.value = response.data.map(vehicle => ({ ...vehicle, checked: false }))
    } else if (activeName.value == '队伍') {
      const response = await axios.get(`${apiBaseUrl.value}/command_issuance/teams/search`, { params: search.value })
      vehicles.value = response.data.map(vehicle => ({ ...vehicle, checked: false }))
    } else {
      const response = await axios.get(`${apiBaseUrl.value}/command_issuance/materials/search`, { params: search.value })
      vehicles.value = response.data.map(vehicle => ({ ...vehicle, checked: false }))
    }
  } catch (error) {
    console.error('搜索失败:', error)
    if (error.response && error.response.status === 404) {
      alert('没有记录')
    } else {
      alert('搜索失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const addNewVehicle = async () => {
  try {
    if (!isEditing.value) {
      await axios.post(apiBaseUrl.value, newVehicle.value)
      alert('创建成功')
    } else {
      await axios.put(`${apiBaseUrl.value}/${newVehicle.value.ID}`, newVehicle.value)
      alert('更新成功')
    }
    closeAddDialog()
    await searchVehicles()
  } catch (error) {
    console.error('创建失败:', error)
    alert('创建失败: ' + (error.response?.data?.message || error.message))
  }
}

const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(item =>
        axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      ))
      selectedIds.value = []
      alert('删除成功')
      table.value.clearSelection()
      await searchVehicles()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// const exportData = async () => {
//   try {
//     const response = await axios.get(`${apiBaseUrl.value}/export`, { responseType: 'blob' })
//     const url = window.URL.createObjectURL(new Blob([response.data]))
//     const link = document.createElement('a')
//     link.href = url
//     link.setAttribute('download', '车辆信息.xlsx')
//     document.body.appendChild(link)
//     link.click()
//   } catch (error) {
//     console.error('导出失败:', error)
//     alert('导出失败: ' + (error.response?.data?.message || error.message))
//   }
// }

// 事件处理函数
const resetSearch = () => {
  search.value = {
    TRANSFER_NUMBER: ''
  }


  searchVehicles()
}
const resetsSearch = () => {

  searchss.value = {
    INSTRUCTION_CODE: ''
  }

  searchVehicles()
}
const openAddDialog = () => {
  isAddDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  newVehicle.value = {
  }
  isEditing.value = false
}



const handleClick = (tab, event) => {
  searchVehicles()
}


// 生命周期钩子
onMounted(() => {
  searchVehicles()
})
</script>


